package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Slf4j
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IBlogService blogService;
    @Resource
    private IUserService userService;

    @Resource
    private IFollowService followService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final DefaultRedisScript<Long> LIKE_SCRIPT;

    static {
        LIKE_SCRIPT = new DefaultRedisScript<>();
        LIKE_SCRIPT.setLocation(new ClassPathResource("like_blog.lua"));
        LIKE_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBolgLiked(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        // 查询笔记
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在！");
        }
        // 查询用户
        queryBlogUser(blog);

        // 查询点赞
        isBolgLiked(blog);
        return Result.ok(blog);
    }

    private void isBolgLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，不需要查询点赞
            return;
        }
        Long userId = user.getId();
        Long blogId = blog.getId();
        // Boolean isMember = stringRedisTemplate.opsForSet().isMember(BLOG_LIKED_KEY + blogId, userId.toString());
        Boolean isMember = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + blogId, userId.toString()) != null;
        blog.setIsLike(Boolean.TRUE.equals(isMember));
    }

    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


    // 可能存在并发安全问题
    @Override
    public Result likeBlog(Long id) {
        // 查询博客信息
        Blog blog = getById(id);
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            log.warn("User is null, Blog ID: {}", blog.getId());
            return Result.fail("请先登录！");
        }

        Long userId = user.getId();
        if (userId == null) {
            blog.setIsLike(false); // 未登录用户默认未点赞
            return Result.ok(blog);
        }
        String key = "blog:liked:" + id;

        // 执行 Lua 脚本
        /*Long result = stringRedisTemplate.execute(
                LIKE_SCRIPT,
                Collections.singletonList(key),
                userId.toString()
        );*/

        // Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Boolean isMember = stringRedisTemplate.opsForZSet().score(key, userId.toString()) != null;
        if (Boolean.FALSE.equals(isMember)) {
            // 如果没点赞，可以点赞
            boolean isSuccess = update()
                    .setSql("liked = liked + 1")
                    .eq("id", id)
                    .update();
            if (isSuccess) {
                // 保存到redis
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        } else {
            // 如果已点赞，取消点赞
            boolean isSuccess = update()
                    .setSql("liked = liked - 1")
                    .eq("id", id)
                    .update();
            if (isSuccess) {
                // 删除
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }

        /*if (result == 1) {
            // 未点赞，需要点赞
            boolean isSuccess = update()
                    .setSql("liked = liked + 1")
                    .eq("id", id)
                    .update();
            if (!isSuccess) {
                // 数据库更新失败，回滚 Redis
                stringRedisTemplate.opsForSet().remove(key, userId.toString());
                return Result.fail("点赞失败，请重试！");
            }
        } else if (result == -1) {
            // 需要取消点赞
            boolean isSuccess = update()
                    .setSql("liked = liked - 1")
                    .eq("id", id)
                    .update();
            if (!isSuccess) {
                // 数据库更新失败，回滚 Redis
                stringRedisTemplate.opsForSet().add(key, userId.toString());
                return Result.fail("取消点赞失败，请重试！");
            }
        }*/
        return Result.ok();
    }

    /**
     * 查询点赞
     *
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY + id;
        // 1. 获取前5名点赞用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        // 2. 解析出用户id
        List<Long> ids = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        // 3. 查询用户
        String str = StrUtil.join(",", ids);
        List<UserDTO> users = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id, " + str + ")") // sql语句中最后的部分
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        // 4. 返回
        return Result.ok(users);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 1. 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2. 保存探店博文
        blogService.save(blog);

        // 3. 查询笔记作者的所有粉丝
        followService.query()
                .eq("follow_user_id", user.getId())
                .list()
                .forEach(follow -> {
                    // 4. 给粉丝发送消息
                    String key = "feed:" + follow.getUserId();
                    stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
                });
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryFollowBlog(Long max, Integer offset) {
        // 1. 获取当前用户
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        String key = "feed:" + userId;
        // 2. 查询收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok();
        }
        // 3. 解析数据
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            ids.add(Long.valueOf(tuple.getValue()));
            long time = tuple.getScore().longValue();
            if (time == minTime) {
                os++;
            } else {
                minTime = time;
                os = 1;
            }
        }
        os = minTime == max ? os : os + offset;

        // 4. 根据id查询blog
        String str = StrUtil.join(",", ids);
        List<Blog> blogs = blogService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id, " + str + ")")
                .list();
        blogs.forEach(blog -> {
            queryBlogUser(blog);
            isBolgLiked(blog);
        });

        // 6. 封装并返回
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);

        // 7. 返回
        return Result.ok(scrollResult);
    }
}
